<?php
    $code = $_GET["js_code"];
    $q = $_GET["q"];
    $appid = "wx06e86c245d8a0c19";
    $secret = "4d1ad47156f9be4820699a07050d724a";
    $grant_type = "authorization_code";
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=$grant_type";
    $html = file_get_contents($url);
    $html = (array)json_decode($html,true);
    // $q = 0;
    // $html = array(
    //     "openid" => "owk575Xek8itLTAXYNdaRmzua6k4",
    //     "session_key" => "456"
    // );
    $fan = 0;
    $openid = $html["openid"];
    if ($q == 0) {
        $a = mysqli_connect("localhost","root","gala123456");
        $db = mysqli_select_db($a,"sheep");
        $sql = "SELECT * FROM `user` WHERE `openid` = '".$html["openid"]."'";
        $query = mysqli_query($a,$sql);
        if (count(array(mysqli_fetch_row($query))) == 0) {
            $fan = 0;
        }else {
            $sql2 = "SELECT * FROM `user` WHERE `openid` = '".$html["openid"]."'";
            $query2 = mysqli_query($a,$sql2);
            while ($row = mysqli_fetch_row($query2)) {
                $ding = 0;
                foreach ($row as $nei) {
                    if ($ding == 1) {
                        if ($nei == $html["session_key"]) {
                            $fan = 1;
                        }else{
                            $a = mysqli_connect("localhost","root","gala123456");
                            $db = mysqli_select_db($a,"sheep");
                            $sql = "UPDATE `user` SET `session_key`='".$html["session_key"]."' WHERE `openid` = '".$html["openid"]."'";
                            $query = mysqli_query($a,$sql);
                            $fan = 1;
                        }
                    }
                    $ding++;
                }
            }
        }
    }else{
        $a = mysqli_connect("localhost","root","gala123456");
        $db = mysqli_select_db($a,"sheep");
        $sql = "INSERT INTO `user`(`openid`, `session_key`,`avatar`) VALUES ('".$html["openid"]."','".$html["session_key"]."',null)";
        $query = mysqli_query($a,$sql);
        $fan = 1;
    }
    mysqli_close($a);
    $arr = array(
        "fan" => $fan,
        "openid" => $openid
    );
    echo json_encode($arr);
?>